import React, { useState, useEffect, useRef, useCallback } from "react";
import { message, Tabs, Table, Spin, Space } from "antd";
import { Panel, FormSelect, UploadModal } from "@/components";
import { useEventListener } from "ahooks";
import dictionary, { echartTypes } from "@/config/character";
import ajax from "@/services";
import "./index.scss";

/**
 * @description 国家数据统计
 **/
export default function NationalData(props) {
  const [tabItems, setTabItems] = useState([
    { label: "币种", key: "item-1" },
    { label: "股票", key: "item-2" },
    { label: "商品", key: "item-3" },
    { label: "债券", key: "item-4" },
    { label: "加密货币", key: "item-5" },
  ]);
  const [ajaxLoading, setAjaxLoading] = useState(false);
  const [resultData, setResultData] = useState([]);
  const [scrollHeight, setScrollHeight] = useState(500);
  const currentTabRef = useRef(tabItems[0].label);
  const resDataRef = useRef([]);
  const prevDataRef = useRef([]);
  const sorterArrRef = useRef([]);
  const intervalRef = useRef(null);
  const sortKeyRef = useRef([]);
  // 动态设置单元格背景色
  const getBackgroundColor = (newValue, oldValue) => {
    if (!oldValue) {
      return "transparent"; // 无变化
    }
    console.log(Number(newValue) > Number(oldValue));
    if (Number(newValue) > Number(oldValue)) {
      return "#ffcccc"; // 红色（上涨）
    }
    if (Number(newValue) < Number(oldValue)) {
      return "#ccffcc"; // 绿色（下跌）
    }
    return "transparent"; // 无变化
  };
  // 获取列表数据
  const getList = (
    params = currentTabRef.current,
    cb = () => {},
    isFirst = false
  ) => {
    if (isFirst) {
      setAjaxLoading(true);
    }
    ajax
      .getNationalData({ tag: params })
      .then(
        (res) => {
          if (res.data.length) {
            let resData = res.data;
            let sortMapArr = new Map();
            let newResData = resData.map((data, index) => {
              let resTitle = data.title.map((item, i) => {
                return {
                  title: item,
                  dataIndex: `national-${index}-${i}`,
                  align: "center",
                  render: (text, record, rowIndex) => {
                    return i === 0 ? (
                      <span
                        className="td-block"
                        onClick={() => {
                          handleSort(
                            `national-${index}-${i}`,
                            record,
                            index,
                            i
                          );
                        }}
                        style={{
                          cursor: "pointer",
                        }}
                      >
                        {text}
                      </span>
                    ) : (
                      <div
                        className="td-block"
                        style={{
                          backgroundColor: getBackgroundColor(
                            text,
                            prevDataRef.current.length
                              ? prevDataRef.current[index]?.value?.[rowIndex]?.[
                                  `national-${index}-${i}`
                                ]
                              : ""
                          ),
                        }}
                      >
                        {text}
                      </div>
                    );
                  },
                };
              });
              let resValue = data.value.map((item, i) => {
                // 设置初始排序状态
                sortMapArr.set(`national-${index}-${i}`, 0);
                let obj = {};
                item.forEach((elememt, i) => {
                  obj[`national-${index}-${i}`] = elememt;
                });
                return { ...obj, key: `national-${index}-${i}` };
              });
              return {
                title: resTitle,
                value: resValue,
              };
            });
            sorterArrRef.current = sortMapArr;
            resDataRef.current = newResData;
            setResultData(newResData);
            cb(newResData);
            handleResize();
          } else {
            setResultData([]);
          }
        },
        (err) => {
          console.log(err);
          setResultData([]);
        }
      )
      .finally(() => {
        setAjaxLoading(false);
        let newTabItems = tabItems.map((item) => {
          return {
            ...item,
            disabled: false,
          };
        });
        setTabItems(newTabItems);
      });
  };
  const onChange = (key) => {
    let newKey = tabItems.find((item) => item.key === key).label;
    currentTabRef.current = newKey;
    getList(newKey, () => {}, true);
    let newTabItems = tabItems.map((item) => {
      return {
        ...item,
        disabled: true,
      };
    });
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    resDataRef.current = [];
    prevDataRef.current = [];
    intervalFun();
    setTabItems(newTabItems);
  };
  // 排序
  const handleSort = (text, data, current, click = false) => {
    let sortOrder = sorterArrRef.current.get(text);
    let newSortOrder = (sortOrder + 1) % 3;
    sorterArrRef.current.set(`${text}`, newSortOrder);
    // Step 1: 提取第一个对象的 statistic1 到 statistic8，并按值升序排序
    if (newSortOrder === 1) {
      sortKeyRef.current = Object.entries(data)
        .filter(
          ([key]) =>
            key.startsWith("national") &&
            (key !== "national-0-0" || !key.includes("-0"))
        ) // 过滤出 statistic1 到 statistic8
        .sort(([, a], [, b]) => Number(a) - Number(b)) // 使用 Number() 进行比较
        .map(([key]) => key); // 仅保留键
    } else if (newSortOrder === 2) {
      sortKeyRef.current = Object.entries(data)
        .filter(
          ([key]) =>
            key.startsWith("national") &&
            (key !== "national-0-0" || !key.includes("-0"))
        ) // 过滤出 statistic1 到 statistic8
        .sort(([, a], [, b]) => Number(b) - Number(a)) // 使用 Number() 进行比较
        .map(([key]) => key); // 仅保留键
    }
    if (!click) {
      allSort(current);
    }
  };
  const allSort = (current) => {
    // Step 2: 根据排序后的 key 顺序调整所有对象
    const reorderedColumns = resDataRef.current.map((params, index) => {
      let newTitle = params.title;
      if (current === index) {
        newTitle = params.title
          .filter(
            (item, i) =>
              item.dataIndex === `national-${index}-${i}` ||
              sortKeyRef.current.includes(item.dataIndex)
          ) // 保留 statistic0 和排序后的键
          .sort(
            (a, b) =>
              sortKeyRef.current.indexOf(a.dataIndex) -
              sortKeyRef.current.indexOf(b.dataIndex)
          ); // 根据排序后的索引重新排列
      }

      return {
        title: newTitle,
        value: params.value,
      };
    });
    resDataRef.current = reorderedColumns;
    setResultData(reorderedColumns);
  };
  const handleResize = () => {
    const tableWarp = document.querySelector(".result-table");
    if (tableWarp) {
      let tableHight = tableWarp.clientHeight - 143;
      setScrollHeight(tableHight);
    }
  };
  const intervalFun = () => {
    console.log(sorterArrRef.current);
    intervalRef.current = setInterval(() => {
      getList(currentTabRef.current, (newData) => {
        prevDataRef.current = resDataRef.current; // 保存当前数据为上一次的数据
        setResultData(newData);
      });
    }, nationInterval); // 每2秒请求一次接口
  };
  useEffect(() => {
    getList(currentTabRef.current, () => {}, true);
    intervalFun();
    return () => clearInterval(intervalRef.current);
  }, []);
  useEventListener("resize", handleResize, { target: window });

  return (
    <div className="national-data-page">
      <Panel className="result-body">
        <div className="result-header">
          <Tabs onChange={onChange} type="card" items={tabItems} />
        </div>
        <div className="result-table">
          {ajaxLoading ? (
            <div style={{ textAlign: "center" }}>
              <Spin tip="加载中..."></Spin>
            </div>
          ) : (
            resultData.length &&
            resultData.map((item, index) => {
              return (
                <Table
                  className="national-table"
                  key={index + "national-data"}
                  scroll={{ y: scrollHeight, x: "auto" }}
                  columns={item.title}
                  dataSource={item.value}
                  bordered
                  pagination={false}
                  rowClassName={(record, index) =>
                    (index + 1) % 2 === 0 ? "even-row" : "odd-row"
                  }
                />
              );
            })
          )}
        </div>
      </Panel>
    </div>
  );
}
